<template>
  <div class="place-order-wrap">
    <!-- 头部导航 -->
    <w-bread-nav title="订单中心"></w-bread-nav>
    <!-- 主内容区域 -->
    <div class="app-container">
      <!-- 管理地址 -->
      <div class="address-operate clearfix">
        <p class="fl">确认收货地址</p>
        <button type="button" class="btn-ghost main fr" @click="$router.push('/my/addressmanager')">收货地址管理</button>
      </div>
      <!-- 地址选择 -->
      <div class="address-wrap clearfix">
        <w-radio v-for="(item, index) in allAddress" 
          :key="index" 
          v-model="checkedAddress" 
          :label="item.id" 
          name="address">
          <span>{{item.provinceName}}省 {{item.areaName}} {{item.cityName}} {{item.area_info}}</span>
          <span>（{{item.trueName}}）</span>
          <span class="phone">{{item.mobile}}</span>
          <span class="address-btn" v-if="item.default_val">默认地址</span>
        </w-radio>
        <button type="button" class="btn-ghost main" @click="$router.push('/my/newaddress')">使用新地址</button>
      </div>
      <!-- 商品订单 -->
      <div class="section" v-for="(goods, goodindex) in orderForm.storeVoList" :key="goodindex">
        <table class="table border">
          <caption>{{goods.storeName}}</caption>
          <!-- 导航信息 -->
          <thead>
            <tr>
              <th width="360">货品信息</th>
              <th>数量</th>
              <th>单价</th>
              <th>金额</th>
            </tr>
          </thead>
          <!-- 商品列表 -->
          <tbody v-for="(list, listIndex) in goods.goodsList" :key="listIndex">
            <tr class="goods" v-for="(gsp, gspIndex) in list.goodsGsp" :key="gspIndex">
              <!-- {{list.goodsGsp}} -->
              <td class="clearfix info">
                <img class="fl" v-lazy="list.goodsPhotoPath || list.goodsMainPhotoPath">
                <div class="fl desc">
                  <p class="tit">{{list.goodsName}}</p>
                  <span class="goods-type" v-if="list.goodsType == 1">伙拼</span>
                  <p>
                    <span>
                      {{gsp.specColor}} {{gsp.specSize}}
                    </span>
                  </p>
                </div>
              </td>
              <td>{{gsp.count || 0}}</td>
              <td class="price">￥{{gsp.singlePrice || gsp.nowPrice || 0 | currency}}</td>
              <td class="total">￥{{gsp.singleTotalPrice || gsp.price || 0 | currency}}</td>
            </tr>
          </tbody>
          <!-- 单个商品订单统计 -->
          <tfoot>
            <tr>
              <td colspan="4" class="clearfix">
                <div class="fl">
                  <input class="form-control" v-model="goods.msg" type="text" placeholder="给卖家留言" maxlength="50">
                </div>
                <div class="fr all-total">
                  <p>
                    <span>运费共计：</span>
                    <strong>￥{{goods.shipPrice || goods.goodsShipPrice || 0 | currency}}</strong>
                  </p>
                  <p>
                    <span>货品总金额：</span>
                    <strong class="total-price">￥{{goods.totalPrice || goods.goodsPrice || 0 | currency}}</strong>
                  </p>
                </div>
              </td>
            </tr>
          </tfoot>
        </table>
      </div>
      <!-- 立即购买合计 -->
      <div class="section">
        <div class="border clearing clearfix">
          <p class="fl">合计</p>
          <p class="fl">共计{{orderForm.totalCount || 0}}件</p>
          <p class="fl">货品金额：
            <strong class="c-main">{{orderForm.totalPrice || 0 | currency}}元</strong>
            <span class="c-main">（运费：{{orderForm.shipPrice || 0 | currency}}元 ）</span>
          </p>
          <w-button type="main" class="fr" @on-click="submitOrderByBuy()">应付总金额{{orderForm.payPrice || 0 | currency}}元</w-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { mapActions, mapGetters } from 'vuex'
  import { apiOrderByToken, apiEditOrderMsg, apiAddOrders, apiShipPrice } from 'js/api'
  import { session } from '../common/util'
  import app from '../main'

  // 错误信息常量
  const ERROR_MESSAGE = {
    ERROR_GOODS_INFO: '商品信息异常',
    NO_ADDRESS: '请选择地址',
    FAIL_BUILD_ORDER: '未成功生成订单，请重试'
  }

  export default {
    data() {
      return {
        // 当前是否是从购物车进来的
        isCart: (this.$route.query.origin == 'cart'),
        // 订单信息（立即购买的订单）
        orderForm: {},
        address: '', // 选中的地址,
        oOrderList: {}, // 订单列表
        priceList: [], // 邮费价格列表
        commitOrderList: [] // ids封装数据
      }
    },
    created() {
      const _this = this
      // 查询地址
      this.fetchAllAddress({
        token: this.token,
        callback(list) {
          if (!list.length) {
            _this.$toast('请先新增一条地址', () => {
              _this.$router.push('/my/newaddress?redirect=/placeorder?origin=cart')
            })
          }
        }
      })

      // 如果当前是购物车进来的，则等待获取地址后加载数据
      if (this.isCart) {
        return
      }
      // 如果当前是立即购买进来的
      this.getOrderFormFromimmediatelyBuy()
    },
    computed: {
      ...mapGetters(['allAddress', 'token']),
      checkedAddress: { // 设置选中地址
        get() {
          if (this.address) return this.address
          for (let i in this.allAddress) {
            const address = this.allAddress[i]
            if (address.default_val) {
              this.address = address.id
              return address.id
            }
          }
        },
        set(newVal) {
          this.address = newVal
        }
      },
      orderGoodsList() { // 获取订单商品列表
        const orderList = this.oOrderList.orderFormList || []
        if (orderList.length && orderList[0].goodsInfo) {
          const oGoodsInfo = JSON.parse(orderList[0].goodsInfo)[0]
          return oGoodsInfo
        }
      },
      /**
       * 获取查询地址需要的商品列表
       */
      addressGoodsList() {
        // 商品id和数量的列表
        let list = []

        // 遍历立即购买的数据，将商品id和商品数量取出来
        if (this.orderForm.storeVoList && this.orderForm.storeVoList.length > 0) {
          this.orderForm.storeVoList.forEach(v1 => {
            // 当前记录当前商品的id和数量
            let goodsItem = {}
            v1.goodsList.forEach(list => {
              goodsItem = {
                id: list.goodsId,
                count: 0
              }
              // 记录当前商品的总数量
              list.goodsGsp.forEach((v2) => {
                goodsItem.count += Number(v2.count)
              })
            })

            // 将对象放到list中
            list.push(goodsItem)
          })
        }

        // 返回数据
        return list
      }
    },
    methods: {
      ...mapActions(['fetchAllAddress']),
      // 根据订单ID获取订单信息
      fetchOrderByToken(token, addressId) {
        apiOrderByToken(token, '2', addressId).then(data => {
          // 将购物车数据装换成可以结算的数据
          this.orderForm = {
            accessToken: this.$store.getters.token,
            orderType: 'web',
            payType: 'online',
            invoiceType: 0,
            invoice: '',
            transport: '快递',
            orderForm: 0,
            receiverAddrId: `${addressId}`,
            storeVoList: data.goodsVoList,
            totalCount: 0,
            totalPrice: 0,
            shipPrice: 0,
            payPrice: 0,
            goodscartId: [] // 购物车Id
          }
          // 如果没有获取到商品的值，跳转到购物车页面
          if (!data.goodsVoList || data.goodsVoList.length == 0) {
            this.$router.go(-1)
            return
          }

          // 遍历商品列表
          this.orderForm.storeVoList.forEach((v) => {
            this.$set(v, 'msg', '')
            // 计算总数量
            v.goodsList.forEach(list => {
              list.goodsGsp.forEach(gsp => {
                this.orderForm.totalCount += Number(gsp.count)
                this.orderForm.goodscartId.push(gsp.goodsCartId)
              })
              // 转换goodsId为string类型
              list.goodsId = list.goodsId.toString()
            })
            // v.goodsGsp.forEach(gsp => {
            //   this.orderForm.totalCount += Number(gsp.count)
            // })
            // 累加总运费
            this.orderForm.shipPrice += parseFloat(v.goodsShipPrice || 0)

            // 累加总价格
            this.orderForm.goodsPrice += parseFloat(v.goodsPrice)

            // 货品金额totalPrice
            this.orderForm.totalPrice += parseFloat(v.goodsPrice)

            // 应付总金额 payPrice
            this.orderForm.payPrice = this.orderForm.totalPrice + this.orderForm.shipPrice
          })
        })
      },
      // 修改订单留言并提交去付款
      onSubmitOrder(ids, price) {
        const params = this.commitOrderList
        apiEditOrderMsg(this.token, params).then(data => {
          this.$router.push(`/payment?ids=${ids}&price=${price}`)
        })
      },
      /**
       * 提交立即购买的订单
       */
      submitOrderByBuy() {
        // 如果没有选择地址
        if (!this.address) {
          app.$toast(ERROR_MESSAGE.NO_ADDRESS)
          return
        }

        // 商品信息有问题
        if (!this.orderForm.storeVoList || this.orderForm.storeVoList.length == 0) {
          this.$toast(ERROR_MESSAGE.ERROR_GOODS_INFO)

          // 如果有重定向链接
          if (this.$route.query.redirect) {
            setTimeout(() => {
              this.$router.push(this.$route.query.redirect)
            }, 1000)
          }
          return
        }

        // 赋值地址信息
        this.orderForm.receiverAddrId = '' + this.address
        // 提交订单
        apiAddOrders(this.orderForm).then((data) => {
          // 如果生成订单成功，则将订单号带到下个页面
          if (!data.ids || data.ids.length == 0) {
            app.$toast(ERROR_MESSAGE.FAIL_BUILD_ORDER)
          }

          // 删除立即购买的数据
          session.remove('confirm-order-info')

          // 跳转路由
          this.$router.push(`/payment?ids=${data.ids.join(',')}`)
        })
      },

      /**
       * 获取快递费
       *
       * @params { Number } id 收货地址id
       */
      queryDelieryFee(id) {
        // 如果当前是购物车，则不用查询接口
        if (this.isCart) {
          return
        }

        // 如果查询地址用的商品组合不存在，则提示
        if (this.addressGoodsList.length == 0) {
          // 如果有重定向链接，则跳转
          if (this.$route.query.redirect) {
            this.$router.push(this.$route.query.redirect)
          }
          return
        }

        // 查询价格
        apiShipPrice(id, this.addressGoodsList).then((data) => {
          // 获取价格列表
          this.priceList = data.singlePriceList

          // 添加邮费
          this.orderForm.shipPrice = data.shipPrice || 0

          // 计算总价格
          this.orderForm.payPrice = this.orderForm.totalPrice + parseFloat(data.shipPrice)

          // 添加店铺下的所有商品的邮费
          this.orderForm.storeVoList.forEach((v) => {
            // 清空
            v.shipPrice = data.shipPrice
          })
        })
      },

      /**
       * 通过商品id来获取邮费
       * @param  {[type]} id [description]
       * @return {[type]}    [description]
       */
      getShipPriceById(id) {
        // 获取过滤后的价格
        let price = this.priceList.filter((v) => {
          return v.goodsId == id
        })

        // 如果价格存在，则直接返回价格
        if (price && price.length > 0) {
          return (price[0].singleGoodsPrice || 0)
        }
        return 0
      },

      /**
       * 从缓存中去立即购买的数据
       *
       * @return { Boolean } true: 成功获取到数据，false：没有获取到数据
       */
      getOrderFormFromimmediatelyBuy() {
        // debugger
        // 从缓存中获取立即购买的数据
        let orderForm = session.get('confirm-order-info')

        // 如果从缓存中获取立即购买数据，则将其赋值给列表
        if (orderForm) {
          this.orderForm = orderForm

          // 生产展示用的数据
          this.setTotalPrice()
          return true
        }

        // 如果没取到，则返回false
        return false
      },

      /**
       * 设置订单的总价格和总数量
       */
      setTotalPrice() {
        this.$set(this.orderForm, 'totalPrice', 0)
        this.$set(this.orderForm, 'shipPrice', 0)
        this.$set(this.orderForm, 'totalCount', 0)
        // 遍历商品数据
        this.orderForm.storeVoList.forEach(v => {
          // 累加总价格
          this.orderForm.totalPrice += parseFloat(v.totalPrice || '0')
          // 累计总数量
          this.orderForm.totalCount += parseFloat(v.totalCount || '0')
          // 累计总运费
          this.orderForm.shipPrice += parseFloat(v.shipPrice || '0')
        })

        // 设置支付价格
        this.$set(this.orderForm, 'payPrice', this.orderForm.totalPrice + this.orderForm.shipPrice)
      }
    },
    watch: {
      // 监视地址的变化去请求数据
      address(newVal, oldVal) {
        // 如果当前是购物车，则请求订单数据
        if (this.isCart) {
          this.fetchOrderByToken(this.$store.getters.token, '' + this.address)
          return
        }
        // 如果是立即购买，则请求运费，将其累加到订单上
        this.queryDelieryFee('' + this.address)
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../scss/_var.scss';
  .place-order-wrap{
    background: $color-white;
  }
  .ml25 {
    margin-left: 25px;
  }

  .section {
    margin-top: 20px;
    background: $color-white;
    .border {
      border: 1px solid #ddd;
    }
  }

  .lh {
    line-height: 1.4;
  }

  .address-operate {
    height: 30px;
    font-size: 14px;
    margin-top: 10px;
    margin-bottom: 10px;
    .btn-ghost {
      height: 30px;
    }
    .fl {
      line-height: 30px;
    }
  }

  .address-wrap {
    padding: 0 20px 30px 20px;
    font-size: 12px;
    background: $color-white;
    // border: 1px solid #ddd;
    p {
      padding-right: 20px;
      padding-top: 20px;
    }
    label {
      display: block;
      padding-top: 20px;
    }
    .phone {
      margin-left: 20px;
    }
    .address-btn {
      margin-left: 16px;
      color: $color-main;
    }
    .btn-ghost {
      height: 30px;
      margin-left: 7px;
      margin-top: 20px;
    }
  }

  .table {
    caption {
      padding: 16px 0 16px 24px;
      border: 1px solid #ddd;
      border-bottom-width: 0;
      font-size: 16px;
    }
    thead {
      th {
        border-bottom-width: 1px;
        padding: 8px;
        font-weight: 400;
      }
    }
    tbody {
      td {
        padding: 16px 24px;
      }
      .goods {
        .info {
          text-align: left;
        }
        img {
          width: 80px;
          height: 80px;
        }
        .price {
          color: $color-main;
        }
        .total {
          color: $color-main;
        }
        .desc {
          margin-left: 20px;
          width: 180px;
          .tit {
            height: 48px;
            line-height: 22px;
            margin-bottom: 0;
            white-space: pre-wrap;
            overflow: hidden;
          }
          .goods-type{
            color:$color-white;
            background: $color-main;
            padding:2px 5px;
            margin-bottom: 5px;
            display: inline-block;
          }
        }
      }
    }
    tfoot {
      td {
        padding: 12px 24px;
      }
      .form-control {
        display: inline-block;
        width: 442px;
        height: 30px;
        font-size: 12px;
      }
      .fl {
        padding-top: 10px;
      }
      .fr {
        margin-right: 36px;
        line-height: 24px;
      }
      .all-total {
        font-size: 14px;
        text-align: left;
        span {
          display: inline-block;
          width: 80px;
          text-align: right;
        }
      }
      .total-price {
        color: $color-main;
      }
    }
  }

  .clearing {
    padding: 20px 48px 20px 24px;
    font-size: 14px;
    .main {
      border-radius: 3px;
      width: auto;
      padding: 0 20px;
      font-size: 16px;
    }
    p {
      line-height: 38px;
      &:first-of-type {
        font-size: 16px;
      }
      &:nth-of-type(2) {
        margin-left: 90px;
      }
      &:nth-of-type(3) {
        margin-left: 100px;
        strong {
          font-size: 16px;
        }
      }
    }
  }
</style>